﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System.Collections;
using System.Linq.Dynamic.Core;
using System.Linq.Expressions;
using Volo.Abp.AspNetCore.Mvc;
using Volo.Abp.Domain.Repositories;
using Volo.Abp.Linq;
using YAKEJI.Abp.Domain.Repositories;
using YAKEJI.Xaf.Numbers;
using YAPACS.BusinessObjects.Exams;
using YAPACS.BusinessObjects.Managements.Devices;
using YAPACS.BusinessObjects.Managements.Exams;
using YAPACS.BusinessObjects.Managements.Templates;
using YAPACS.Organizations;
using YAPACS.RisServer.Services.Dtos.Templates;

namespace YAPACS.RisServer.Controllers;
[Authorize]
[Route("api/diagnosis-template")]
public class DiagnosisTemplateController : AbpControllerBase
{
    private readonly IRepository<DiagnosisTemplate, Guid> _diagnosisTemplateRepository;
    private readonly IRepository<DiagnosisTemplateHistory, Guid> _diagnosisTemplateHistoryRepository;
    private readonly IRepository<ApplicationUser, Guid> _userRepository;
    private readonly IRepository<Department, Guid> _departmentRepository;
    private readonly IRepository<DeviceType, Guid> _deviceTypeRepository;
    private readonly IRepository<Report, Guid> _reportRepository;
    private readonly INumberService _numberService;
    private readonly IAsyncQueryableExecuter _queryableExecuter;
    private readonly ICurrentUserOrganization _currentUserOrganization;

    public DiagnosisTemplateController(
        IRepository<DiagnosisTemplate, Guid> diagnosisTemplateRepository,
        IRepository<DiagnosisTemplateHistory, Guid> diagnosisTemplateHistoryRepository,
        IRepository<ApplicationUser, Guid> userRepository,
        IRepository<Department, Guid> departmentRepository,
        IRepository<DeviceType, Guid> deviceTypeRepository,
        IRepository<Report, Guid> reportRepository,
        INumberService numberService,
        IAsyncQueryableExecuter queryableExecuter,
        ICurrentUserOrganization currentUserOrganization)
    {
        _diagnosisTemplateRepository = diagnosisTemplateRepository;
        _diagnosisTemplateHistoryRepository = diagnosisTemplateHistoryRepository;
        _userRepository = userRepository;
        _departmentRepository = departmentRepository;
        _deviceTypeRepository = deviceTypeRepository;
        _reportRepository = reportRepository;
        _numberService = numberService;
        _queryableExecuter = queryableExecuter;
        _currentUserOrganization = currentUserOrganization;
    }

    private static List<DiagnosisTemplate> GetChildrenTemplates(DiagnosisTemplate template)
    {
        var templates = new List<DiagnosisTemplate>();

        foreach (var item in template.Children)
        {
            templates.Add(item);
            templates.AddRange(GetChildrenTemplates(item));
        }

        return templates;
    }

    private async Task DeleteTemplateAsync(DiagnosisTemplate template)
    {
        if (template.IsDirectory)
        {
            foreach (var child in template.Children)
            {
                await DeleteTemplateAsync(child);
            }
        }
        await _diagnosisTemplateRepository.DeleteAsync(template);
    }

    private async Task<IList> GetCommonTemplatesAsync(string deviceType)
    {
        var templates = new List<object>();

        var historyDirectory = new
        {
            Id = Guid.NewGuid(),
            Name = "历史模板",
            IsExpanded = true,
            IsDirectory = true,
        };

        templates.Add(historyDirectory);

        var commonDirectory = new
        {
            Id = Guid.NewGuid(),
            Name = "常用模板",
            IsExpanded = true,
            IsDirectory = true,
        };

        templates.Add(commonDirectory);

        var query = await _diagnosisTemplateHistoryRepository.GetQueryableAsync();
        query = query
            .Where(x => x.DiagnosisTemplate.DeviceType.Code == deviceType)
            .Where(x => x.User.Oid == _currentUserOrganization.UserId)
            .OrderByDescending(x => x.LastUsedTime)
            .Take(10);

        templates.AddRange((await _queryableExecuter.ToListAsync(query)).Select(x => new
        {
            Id = Guid.NewGuid(),
            HistoryId = x.Id,
            TemplateId = x.DiagnosisTemplate.Id,
            x.DiagnosisTemplate.Name,
            ParentId = historyDirectory.Id,
            BodyParty = x.DiagnosisTemplate.BodyParties
        }));

        query = await _diagnosisTemplateHistoryRepository.GetQueryableAsync();
        query = query
            .Where(x => x.DiagnosisTemplate.DeviceType.Code == deviceType)
            .Where(x => x.User.Oid == _currentUserOrganization.UserId)
            .OrderByDescending(x => x.UsedTimes)
            .Take(10);

        templates.AddRange((await _queryableExecuter.ToListAsync(query)).Select(x => new
        {
            Id = Guid.NewGuid(),
            HistoryId = x.Id,
            TemplateId = x.DiagnosisTemplate.Id,
            x.DiagnosisTemplate.Name,
            ParentId = commonDirectory.Id,
            BodyParty = x.DiagnosisTemplate.BodyParties
        }));

        return templates;
    }

    private async Task<IList> GetTemplatesAsync(string deviceType, bool enableFilter, List<string> examBodyParties, Expression<Func<DiagnosisTemplate, bool>> predicate)
    {
        var templates = new List<DiagnosisTemplate>();

        var query = await _diagnosisTemplateRepository.GetQueryableAsync();
        query = query
            .Where(x => x.DeviceType.Code == deviceType)
            .Where(predicate)
            .WhereIf(enableFilter, x => x.Parent == null && x.IsDirectory)
            .OrderBy(x => x.Order);

        var list = await _queryableExecuter.ToListAsync(query);

        if (enableFilter)
        {
            foreach (var item in list)
            {
                var itemBodyParties = item.BodyParties.Split(',').Select(x => x.Trim());
                if (examBodyParties.Exists(itemBodyParties.Contains))
                {
                    templates.Add(item);
                }
            }

            foreach (var template in templates.ToList())
            {
                templates.AddRange(GetChildrenTemplates(template));
            }
        }
        else
        {
            templates = list;
        }

        return templates.Select(x => new
        {
            x.Id,
            TemplateId = x.Id,
            x.Name,
            ParentId = x.Parent?.Id,
            x.IsDirectory,
            x.Order,
            BodyParty = x.BodyParties
        }).ToList();
    }

    private async Task<IList> GetTemplateDirectoriesAsync(string deviceType, Expression<Func<DiagnosisTemplate, bool>> predicate)
    {
        var query = await _diagnosisTemplateRepository.GetQueryableAsync();
        query = query
            .Where(x => x.DeviceType.Code == deviceType)
            .Where(x => x.IsDirectory)
            .Where(predicate)
            .OrderBy(x => x.Order);

        return (await _queryableExecuter.ToListAsync(query)).Select(x => new
        {
            x.Id,
            TemplateId = x.Id,
            x.Name,
            ParentId = x.Parent?.Id
        }).ToList();
    }

    private async Task<long> GetMaxOrderAsync(string deviceType, DiagnosisTemplate parent, Expression<Func<DiagnosisTemplate, bool>> predicate)
    {
        var query = await _diagnosisTemplateRepository.GetQueryableAsync();
        query = query.Where(t => t.DeviceType.Code == deviceType);
        query = query.Where(predicate);

        if (parent != null)
        {
            query = query.Where(t => t.Parent.Id == parent.Id);
        }

        return await _queryableExecuter.MaxAsync(query.OrderBy(t => t.Order).Select(t => t.Order)) + 100;
    }

    private async Task<DiagnosisTemplate> CloneTemplateAsync(DiagnosisTemplate template, DiagnosisTemplate directory, ApplicationUser user, Department department, DeviceType deviceType)
    {
        var newTemplate = await _diagnosisTemplateRepository.NewEntityAsync();
        newTemplate.Name = template.Name;
        newTemplate.ApplicableSex = template.ApplicableSex;
        newTemplate.ExamResult = template.ExamResult;
        newTemplate.IsDirectory = template.IsDirectory;
        newTemplate.Parent = directory;
        newTemplate.ImageSeeing = template.ImageSeeing;
        newTemplate.ImageDiagnosis = template.ImageDiagnosis;
        newTemplate.ImageOpinion = template.ImageOpinion;
        newTemplate.User = user;
        newTemplate.Department = department;
        newTemplate.DeviceType = deviceType;

        newTemplate.Code = await _numberService.GetNumberAsync(new NumberOptions
        {
            NumberId = typeof(DiagnosisTemplate).FullName,
            NumberTemplate = "D{0:<INDEX>,00000}",
        }, newTemplate);

        if (user != null)
        {
            newTemplate.Order = await GetMaxOrderAsync(deviceType.Code, newTemplate.Parent, t => t.User.Id == _currentUserOrganization.UserId && t.Department == null);
        }
        else if (department != null)
        {
            newTemplate.Order = await GetMaxOrderAsync(deviceType.Code, newTemplate.Parent, t => t.Department.Id == _currentUserOrganization.DepartmentId && t.User == null);
        }
        else
        {
            newTemplate.Order = await GetMaxOrderAsync(deviceType.Code, newTemplate.Parent, t => t.Department == null && t.User == null);
        }

        if (template.IsDirectory)
        {
            foreach (var child in template.Children)
            {
                await CloneTemplateAsync(child, newTemplate, user, department, deviceType);
            }
        }

        return newTemplate;
    }

    [HttpGet("get-templates")]
    public async Task<IActionResult> GetTemplates([FromQuery] string templateType, [FromQuery] Guid reportId, [FromQuery] bool enableFilter)
    {
        var exam = (await _reportRepository.GetAsync(reportId)).Exam;
        var deviceType = exam.DeviceType.Code;
        var examBodyParties = enableFilter ? exam.ExamBodyParties.Select(e => e.Name?.Trim()).Where(x => !string.IsNullOrWhiteSpace(x)).ToList() : [];
        enableFilter = enableFilter && examBodyParties.Any();
        return Ok(new
        {
            Success = true,
            Data = templateType switch
            {
                "common" => await GetCommonTemplatesAsync(deviceType),
                "user" => await GetTemplatesAsync(deviceType, enableFilter, examBodyParties, x => x.User.Id == _currentUserOrganization.UserId && x.Department == null),
                "department" => await GetTemplatesAsync(deviceType, enableFilter, examBodyParties, x => x.Department.Id == _currentUserOrganization.DepartmentId && x.User == null),
                "public" => await GetTemplatesAsync(deviceType, enableFilter, examBodyParties, x => x.User == null && x.Department == null),
                _ => Array.Empty<object>(),
            }
        });
    }

    [HttpGet("get-template/{id}")]
    public async Task<IActionResult> GetTemplate(Guid id)
    {
        var template = await _diagnosisTemplateRepository.GetAsync(id);
        return Ok(new
        {
            Success = true,
            Data = new TemplateDto
            {
                Id = template.Id.ToString(),
                TemplateId = template.Id.ToString(),
                ExamResult = template.ExamResult switch
                {
                    ExamResult.Negative => 1,
                    ExamResult.Positive => 2,
                    _ => 0
                },
                ApplicableSex = (int)template.ApplicableSex,
                ImageDiagnosis = template.ImageDiagnosis,
                ImageOpinion = template.ImageOpinion,
                ImageSeeing = template.ImageSeeing,
                Name = template.Name,
                ParentId = template.Parent?.Id.ToString()
            }
        });
    }

    [HttpPost("new-template")]
    public async Task<IActionResult> NewTemplate([FromBody] TemplateDto input)
    {
        var exam = (await _reportRepository.GetAsync(input.ReportId)).Exam;
        var template = await _diagnosisTemplateRepository.NewEntityAsync();
        template.Name = input.Name;

        template.ApplicableSex = input.ApplicableSex switch
        {
            1 => ApplicableSex.Male,
            2 => ApplicableSex.Female,
            _ => ApplicableSex.None
        };

        template.ExamResult = input.ExamResult switch
        {
            1 => ExamResult.Negative,
            2 => ExamResult.Positive,
            _ => null
        };

        if (Guid.TryParse(input.ParentId, out var parentId))
        {
            // 如果选中的是模板，则使用该模板的父级作为新建模板的父级
            var parent = await _diagnosisTemplateRepository.FindAsync(parentId);
            if (parent != null)
            {
                template.Parent = parent.IsDirectory ? parent : parent.Parent;
            }
        }

        template.ImageSeeing = input.ImageSeeing;
        template.ImageDiagnosis = input.ImageDiagnosis;
        template.ImageOpinion = input.ImageOpinion;

        template.DeviceType = await _deviceTypeRepository.FindAsync(d => d.Code == exam.DeviceType.Code);

        switch (input.Type)
        {
            case "user":
                template.Order = await GetMaxOrderAsync(input.Type, template.Parent, t => t.User.Id == _currentUserOrganization.UserId && t.Department == null);
                template.User = await _userRepository.FindAsync(_currentUserOrganization.UserId);
                break;
            case "department":
                template.Order = await GetMaxOrderAsync(input.Type, template.Parent, t => t.Department.Id == _currentUserOrganization.DepartmentId && t.User == null);
                template.Department = _currentUserOrganization.DepartmentId.HasValue
                    ? await _departmentRepository.FindAsync(_currentUserOrganization.DepartmentId.Value)
                    : null;
                break;
            default:
                template.Order = await GetMaxOrderAsync(input.Type, template.Parent, t => t.Department == null && t.User == null);
                break;
        }

        template.Code = await _numberService.GetNumberAsync(new NumberOptions
        {
            NumberId = typeof(DiagnosisTemplate).FullName,
            NumberTemplate = "D{0:<INDEX>,00000}",
        }, template);

        return Ok(new
        {
            Success = true,
            Data = new TemplateDto
            {
                Id = template.Id.ToString(),
                TemplateId = template.Id.ToString(),
                ParentId = template.Parent?.Id.ToString(),
                Name = template.Name,
            }
        });
    }

    [HttpPost("new-template-directory")]
    public async Task<IActionResult> NewTemplateDirectory([FromBody] TemplateDirectoryDto input)
    {
        var exam = (await _reportRepository.GetAsync(input.ReportId)).Exam;
        var template = await _diagnosisTemplateRepository.NewEntityAsync();
        template.Name = input.Name;
        template.BodyParties = input.BodyParty;
        template.IsDirectory = true;

        if (Guid.TryParse(input.ParentId, out var parentId))
        {
            template.Parent = await _diagnosisTemplateRepository.FindAsync(parentId);
        }

        template.DeviceType = await _deviceTypeRepository.FindAsync(d => d.Code == exam.DeviceType.Code);

        switch (input.Type)
        {
            case "user":
                template.Order = await GetMaxOrderAsync(input.Type, template.Parent, t => t.User.Id == _currentUserOrganization.UserId && t.Department == null);
                template.User = await _userRepository.FindAsync(_currentUserOrganization.UserId);
                break;
            case "department":
                template.Order = await GetMaxOrderAsync(input.Type, template.Parent, t => t.Department.Id == _currentUserOrganization.DepartmentId && t.User == null);
                template.Department = _currentUserOrganization.DepartmentId.HasValue
                    ? await _departmentRepository.FindAsync(_currentUserOrganization.DepartmentId.Value)
                    : null;
                break;
            default:
                template.Order = await GetMaxOrderAsync(input.Type, template.Parent, t => t.Department == null && t.User == null);
                break;
        }

        template.Code = await _numberService.GetNumberAsync(new NumberOptions
        {
            NumberId = typeof(DiagnosisTemplate).FullName,
            NumberTemplate = "D{0:<INDEX>,00000}",
        }, template);

        return Ok(new
        {
            Success = true,
            Data = new TemplateDirectoryDto
            {
                Id = template.Id.ToString(),
                TemplateId = template.Id.ToString(),
                ParentId = template.Parent?.Id.ToString(),
                Name = template.Name,
                IsDirectory = template.IsDirectory
            }
        });
    }

    [HttpPost("update-template")]
    public async Task<IActionResult> UpdateTemplate([FromBody] TemplateDto input)
    {
        if (Guid.TryParse(input.Id, out var templateId))
        {
            var template = await _diagnosisTemplateRepository.FindAsync(templateId);
            if (template != null)
            {
                template.Name = input.Name;

                template.ApplicableSex = input.ApplicableSex switch
                {
                    1 => ApplicableSex.Male,
                    2 => ApplicableSex.Female,
                    _ => ApplicableSex.None
                };

                template.ExamResult = input.ExamResult switch
                {
                    1 => ExamResult.Negative,
                    2 => ExamResult.Positive,
                    _ => null
                };

                template.ImageSeeing = input.ImageSeeing;
                template.ImageDiagnosis = input.ImageDiagnosis;
                template.ImageOpinion = input.ImageOpinion;

                return Ok(new
                {
                    Success = true,
                    Data = new TemplateDto
                    {
                        Id = template.Id.ToString(),
                        TemplateId = template.Id.ToString(),
                        ParentId = template.Parent?.Id.ToString(),
                        Name = template.Name,
                    }
                });
            }
        }

        return Ok(new
        {
            Success = false
        });
    }

    [HttpPost("update-template-directory")]
    public async Task<IActionResult> UpdateTemplateDirectory([FromBody] TemplateDirectoryDto input)
    {
        if (Guid.TryParse(input.Id, out var templateId))
        {
            var template = await _diagnosisTemplateRepository.FindAsync(templateId);
            if (template != null)
            {
                template.Name = input.Name;
                template.BodyParties = input.BodyParty;

                return Ok(new
                {
                    Success = true,
                    Data = new TemplateDirectoryDto
                    {
                        Id = template.Id.ToString(),
                        TemplateId = template.Id.ToString(),
                        ParentId = template.Parent?.Id.ToString(),
                        Name = template.Name,
                        BodyParty = template.BodyParties,
                        IsDirectory = template.IsDirectory
                    }
                });
            }
        }

        return Ok(new
        {
            Success = false
        });
    }

    [HttpDelete("delete-template")]
    public async Task DeleteTemplate([FromQuery] string id, [FromQuery] string historyId)
    {
        if (!string.IsNullOrWhiteSpace(historyId))
        {
            if (Guid.TryParse(historyId, out var templateHistoryId))
            {
                await _diagnosisTemplateHistoryRepository.DeleteAsync(templateHistoryId);
            };
        }
        else if (Guid.TryParse(id, out var templateId))
        {
            var template = await _diagnosisTemplateRepository.FindAsync(templateId);
            if (template != null)
            {
                await DeleteTemplateAsync(template);
            }
        }
    }

    [HttpPost("apply-template/{id}")]
    public async Task ApplyTemplate(Guid id)
    {
        var template = await _diagnosisTemplateRepository.GetAsync(id);
        if (template != null)
        {
            var historyTemplate = await _diagnosisTemplateHistoryRepository.FindAsync(t => t.DiagnosisTemplate.Id == template.Id);
            historyTemplate ??= await _diagnosisTemplateHistoryRepository.NewEntityAsync();
            historyTemplate.User = await _userRepository.FindAsync(_currentUserOrganization.UserId);
            historyTemplate.DiagnosisTemplate = template;
            historyTemplate.LastUsedTime = Clock.Now;
            historyTemplate.UsedTimes += 1;
        }
    }

    [HttpGet("get-full-template")]
    public async Task<IActionResult> GetFullTemplate([FromQuery] string id)
    {
        if (Guid.TryParse(id, out var templateId))
        {
            var template = await _diagnosisTemplateRepository.FindAsync(templateId);
            if (template != null)
            {
                return Ok(new
                {
                    Success = true,
                    Data = new TemplateDto
                    {
                        Id = template.Id.ToString(),
                        TemplateId = template.Id.ToString(),
                        ParentId = template.Parent?.Id.ToString(),
                        Name = template.Name,
                        ApplicableSex = (int)template.ApplicableSex,
                        ExamResult = template.ExamResult.HasValue ? ((int)template.ExamResult.Value) + 1 : 0,
                        ImageSeeing = template.ImageSeeing,
                        ImageDiagnosis = template.ImageDiagnosis,
                        ImageOpinion = template.ImageOpinion,
                    }
                });
            }
        }

        return Ok(new
        {
            Success = false
        });
    }

    [HttpPost("sort-template")]
    public async Task<IActionResult> SortTemplate([FromBody] SortTemplateDto input)
    {
        if (Guid.TryParse(input.FromId, out var fromId))
        {
            var fromTemplate = await _diagnosisTemplateRepository.FindAsync(fromId);
            if (fromTemplate != null)
            {
                DiagnosisTemplate toTemplate = null;
                if (Guid.TryParse(input.ToId, out var toId))
                {
                    toTemplate = await _diagnosisTemplateRepository.FindAsync(toId);
                }

                if (toTemplate != null)
                {
                    if (input.IsInside)
                    {
                        if (toTemplate.IsDirectory)
                        {
                            fromTemplate.Parent = toTemplate;
                        }
                    }
                    else
                    {
                        var query = await _diagnosisTemplateRepository.GetQueryableAsync();
                        query = query.Where(t => t.Parent == toTemplate.Parent);
                        query = query.Where(t => t.Order < toTemplate.Order);
                        query = query.OrderByDescending(t => t.Order);

                        var order = toTemplate.Order / 2;
                        var prevTemplate = await _queryableExecuter.FirstOrDefaultAsync(query);
                        if (prevTemplate != null)
                        {
                            order = prevTemplate.Order + (toTemplate.Order - prevTemplate.Order) / 2;
                        }

                        fromTemplate.Order = order;
                    }
                }
                else
                {
                    fromTemplate.Parent = null;
                }

                if (input.IsInside || fromTemplate.Parent == null)
                {
                    if (fromTemplate.User != null)
                    {
                        fromTemplate.Order = await GetMaxOrderAsync(fromTemplate.DeviceType.Code, fromTemplate.Parent, t => t.User.Id == fromTemplate.User.Id && t.Department == null);
                    }
                    else if (fromTemplate.Department != null)
                    {
                        fromTemplate.Order = await GetMaxOrderAsync(fromTemplate.DeviceType.Code, fromTemplate.Parent, t => t.Department.Id == fromTemplate.Department.Id && t.User == null);
                    }
                    else
                    {
                        fromTemplate.Order = await GetMaxOrderAsync(fromTemplate.DeviceType.Code, fromTemplate.Parent, t => t.Department == null && t.User == null);
                    }
                }

                return Ok(new
                {
                    Success = true,
                    Data = new TemplateDto
                    {
                        Id = fromTemplate.Id.ToString(),
                        TemplateId = fromTemplate.Id.ToString(),
                        ParentId = fromTemplate.Parent?.Id.ToString(),
                        Name = fromTemplate.Name,
                    }
                });
            }
        }

        return Ok(new
        {
            Success = false
        });
    }

    [HttpGet("get-template-directories")]
    public async Task<IActionResult> GetTemplateDirectories([FromQuery] string type, [FromQuery] Guid reportId)
    {
        var exam = (await _reportRepository.GetAsync(reportId)).Exam;
        return Ok(new
        {
            Success = true,
            Data = type switch
            {
                "user" => await GetTemplateDirectoriesAsync(exam.DeviceType.Code, x => x.User.Id == _currentUserOrganization.UserId),
                "department" => await GetTemplateDirectoriesAsync(exam.DeviceType.Code, x => x.Department.Id == _currentUserOrganization.DepartmentId && x.User == null),
                "public" => await GetTemplateDirectoriesAsync(exam.DeviceType.Code, x => x.User == null && x.Department == null),
                _ => Array.Empty<object>(),
            }
        });
    }

    [HttpPost("clone-template")]
    public async Task<IActionResult> CloneTemplate([FromBody] CloneTemplateDto input)
    {
        if (Guid.TryParse(input.TemplateId, out var templateId))
        {
            var template = await _diagnosisTemplateRepository.FindAsync(templateId);
            if (template != null)
            {
                DiagnosisTemplate directory = null;
                ApplicationUser user = null;
                Department department = null;
                DeviceType deviceType = null;

                if (Guid.TryParse(input.TemplateDirectoryId, out var directoryId))
                {
                    directory = await _diagnosisTemplateRepository.FindAsync(directoryId);
                    if (directory != null)
                    {
                        user = directory.User;
                        department = directory.Department;
                        deviceType = directory.DeviceType;
                    }
                }

                if (directory == null)
                {
                    switch (input.Type)
                    {
                        case "user":
                            user = await _userRepository.FindAsync(_currentUserOrganization.UserId);
                            break;
                        case "department":
                            department = _currentUserOrganization.DepartmentId.HasValue
                                ? await _departmentRepository.FindAsync(_currentUserOrganization.DepartmentId.Value)
                                : null;
                            break;
                    }

                    deviceType = template.DeviceType;
                }

                var newTemplate = await CloneTemplateAsync(template, directory, user, department, deviceType);

                return Ok(new
                {
                    Success = true,
                    Data = new TemplateDto
                    {
                        Id = newTemplate.Id.ToString(),
                        TemplateId = newTemplate.Id.ToString(),
                        ParentId = newTemplate.Parent?.Id.ToString(),
                        Name = newTemplate.Name,
                    }
                });
            }
        }

        return Ok(new
        {
            Success = false
        });
    }
}
